<?php

namespace App\Http\Controllers\Admin;

use App\Services\Admin\PermissionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PermissionController extends AdminBaseController
{
    private $permissionService;

    public function __construct(PermissionService $permissionService)
    {
        $this->permissionService = $permissionService;
    }

    /**
     * 权限列表
     */
    public function list(Request $request): \Illuminate\Http\JsonResponse
    {
        $params = $request->all();
        $data = $this->permissionService->list($params);
        return $this->success($data);
    }

    /**
     * 权限详情
     */
    public function view(int $id): \Illuminate\Http\JsonResponse
    {
        $data = $this->permissionService->view($id);
        return $this->success($data);
    }

    /**
     * 创建权限
     */
    public function create(Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'string|max:255',
        ], [
            'name.required' => '权限名称不能为空',
            'display_name.required' => '显示名称不能为空',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $id = $this->permissionService->create($request->all());
        return $this->success($id);
    }

    /**
     * 更新权限
     */
    public function update(int $id, Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'string|max:255',
            'description' => 'string|max:255',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $rows = $this->permissionService->update($id, $request->all());
        return $this->success($rows);
    }

    /**
     * 删除权限
     */
    public function delete(int $id): \Illuminate\Http\JsonResponse
    {
        $rows = $this->permissionService->delete($id);
        return $this->success($rows);
    }

    /**
     * 生成权限
     */
    public function generate(): \Illuminate\Http\JsonResponse
    {
        $result = $this->permissionService->generatePermissions();
        return $this->success($result);
    }

    /**
     * 获取分组权限列表（用于权限选择组件）
     */
    public function grouped(): \Illuminate\Http\JsonResponse
    {
        $data = $this->permissionService->getGroupedPermissions();
        return $this->success($data);
    }
}
